package com.ilvyou.api.controller;

import com.ilvyou.api.common.Constant;
import com.ilvyou.api.bean.param.AddBank;
import com.ilvyou.api.bean.result.Result;
import com.ilvyou.api.service.BankService;
import com.ilvyou.api.service.UserService;
import com.ilvyou.api.util.RemoteUtil;
import com.ilvyou.core.dao.Criteria;
import com.ilvyou.core.dao.Query;
import com.ilvyou.core.util.StringUtil;
import com.ilvyou.core.util.Util;
import com.ilvyou.data.lhf.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by GuanYuCai on 16/9/17.
 */
@Controller
public class BankController extends BaseController {

    @Autowired
    private BankService bankService;
    @Autowired
    private UserService userService;

    @RequestMapping("/bank/cardList")
    @ResponseBody
    public Result cardList(@RequestParam String token) throws Exception {
        Query query = new Query(AlipayPbankEntity.class,
                "p.actid,p.realname,p.authcode,p.bankid,p.bankcode,p.bankname," +
                "p.banknumber,p.banktype,p.rechargeflag,p.accounttype,p.createdon")
                .leftJoin(AlipayQpcardEntity.class, "q.pkid",
                        new Criteria().add("p.banknumber=q.banknumber"))
                .leftJoin(AlipayBanktypeEntity.class,
                        "b.imgname1 as smallImgName,b.imgpath1 as smallImgPath," +
                                "b.imgname2 as bigImgName,b.imgpath2 as bigImgPath",
                        new Criteria().add("p.bankid=b.bankid"))
                .where(new Criteria().add("p.enableflag=1 and p.lockflag=0 and p.actid=?", getUserId(token)))
                .order("p.createdon desc");
        return success(bankService.getMapList(query));
    }

    @RequestMapping("/bank/bankList")
    @ResponseBody
    public Result bankList(@RequestParam String token) throws Exception {
        Query query = new Query(AlipayBanktypeEntity.class,
                "bankId,bankCode,bankName,imgname1 as smallImgName," +
                        "imgpath1 as smallImgPath,imgname2 as bigImgName,imgpath2 as bigImgPath")
                .where(new Criteria("imgname1 !='' and enableflag=1 and lockflag=0"));
        return success(bankService.getMapList(query));
    }

    @RequestMapping(value = "/bank/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result delete(@RequestParam String token, @RequestParam String card,
                         @RequestParam String paypassword) throws Exception {
        long actId = getUserId(token);
        ScrAlipayEntity alipay = userService.getByPK(ScrAlipayEntity.class, actId);
        AlipayAccountEntity account = userService.getByPK(AlipayAccountEntity.class, actId);

        paypassword = StringUtil.base64Decode(paypassword);
        paypassword = RemoteUtil.getMd5Pwd(paypassword, alipay.getSalt());
        if (!paypassword.equals(account.getPaypassword())) {
            return fail("交易密码不正确");
        }

        bankService.deleteBankCard(account, card);
        return success("");
    }

    @RequestMapping(value = "/bank/add", method = RequestMethod.POST)
    @ResponseBody
    public Result add(HttpServletRequest request, @RequestParam String token, @RequestParam Long sendid,
                      @RequestParam String verifycode) throws Exception {
        AddBank params = Util.fromRequest(request, AddBank.class);
        params.setActid(getUserId(token));

        String err = validateBankCard(params);
        if (!StringUtil.isEmpty(err)) {
            return fail(err + "为空");
        } else if (!StringUtil.isBankCard(params.getCardnumber())) { //验证银行卡是否合法
            return fail("请填写正确的银行卡号");
        } else if (!StringUtil.isMobile(params.getHolderphone())) { //手机号码格式不正确
            return fail("手机号码格式不正确");
        } else if (!userService.verifySmsCode(sendid, verifycode, params.getHolderphone(), Constant.SMSType.ADD_BANKNUM)) {
            return fail("手机验证码不正确");
        }

        AlipayBanktypeEntity bank = bankService.getByPK(AlipayBanktypeEntity.class, params.getBankid());
        if (bank == null) {
            return fail("您输入的银行不存在");
        }

        AlipayPbankEntity pbank = bankService.getByPK(AlipayPbankEntity.class, params.getCardnumber());
        if (pbank != null && pbank.getRechargeflag() != 0) {
            return fail("该银行卡已被绑定");
        }

        bankService.addBankCard(params, pbank, bank);
        return success("");
    }

    private String validateBankCard(AddBank addBank) {
        String err = "";

        if (StringUtil.isEmpty(addBank.getBanktype())) {
            err = "银行卡类型";
        } else if (addBank.getBankid() == null) {
            err = "银行ID";
        } else if (("Debit").equals(addBank.getBanktype()) && StringUtil.isEmpty(addBank.getOpenbankname())) {
            err = "开户行";
        } else if (("Credit").equals(addBank.getBanktype()) && (StringUtil.isEmpty(addBank.getCardverifycode()))) {
            err = "银行卡验证码";
        } else if (("Credit").equals(addBank.getBanktype()) && (StringUtil.isEmpty(addBank.getDuemonth()) || StringUtil.isEmpty(addBank.getDueyear()))) {
            err = "有效期年份或者月份";
        } else if (StringUtil.isEmpty(addBank.getCardnumber())) {
            err = "银行卡号";
        } else if (StringUtil.isEmpty(addBank.getHolderphone())) {
            err = "预留手机号码";
        } else if (addBank.getAccounttype() == null) {
            err = "账户类型";
        } else if (("Debit").equals(addBank.getBanktype()) && "1".equals(addBank.getAccounttype()) && (StringUtil.isEmpty(addBank.getHoldername()))) {
            err = "姓名";
        }
        return err;
    }
}
